package cn.com.yto56.cainiao.exponent.elasticsearch.service.impl;

import cn.com.yto56.basic.framework.plugin.elasticsearch.ElasticSearchStarter;
import cn.com.yto56.cainiao.exponent.common.AgentPoint;
import cn.com.yto56.cainiao.exponent.common.ExponentType;
import cn.com.yto56.cainiao.exponent.common.QueryDSL;
import cn.com.yto56.cainiao.exponent.dto.ExponentRequest;
import cn.com.yto56.cainiao.exponent.dto.QueryESResponse;
import cn.com.yto56.cainiao.exponent.elasticsearch.service.CommonService;
import cn.com.yto56.cainiao.exponent.elasticsearch.service.FrontHandleService;
import cn.com.yto56.cainiao.exponent.elasticsearch.service.TrackService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class TrackServiceImpl implements TrackService {

    @Autowired
    private FrontHandleService frontHandleService;

    @Autowired
    private ElasticSearchStarter starter;

    @Override
    public void accuracy(String mailNo, String data) {
        // 信息准确率
        JSONObject jsonObject = JSON.parseObject(data);
        List<String> list = (List<String>) JSONPath.eval(jsonObject, "$.data.traceDetailList.action");
        if (list != null && list.size() > 0) {
            ExponentRequest req = new ExponentRequest();
            req.setWayBillNo(mailNo);
            req.setExponentType(ExponentType.ACCURACY.getName());
            req.setExponetMsg("代收点信息不准确");
            Set<String> act = new HashSet<>(list);
            if (act.contains("SH_INBOUND")) {
                req.setAgentPoint(AgentPoint.SH_INBOUND);
                updateAgentPoint(req);
            } else if (act.contains("INBOUND")) {
                String operEmpPhone = frontHandleService.queryInbound(mailNo);
                if ("FC".equals(operEmpPhone)) {
                    req.setAgentPoint(AgentPoint.FC);
                    updateAgentPoint(req);
                } else if ("DSFZTG".equals(operEmpPhone)) {
                    req.setAgentPoint(AgentPoint.THIRD);
                    updateAgentPoint(req);
                }
            }
        }
    }

    private void updateAgentPoint(ExponentRequest req) {
        // 更新代办点信息
        String id = CommonService.generateESId(req);
        ClientInterface clientInterface = starter.getRestClient();
        QueryESResponse response = CommonService.searchById(clientInterface, id);
        if (response != null) {
            String entity = String.format(QueryDSL.ACCURACY_UPDATE_AGENT_POINT, req.getAgentPoint());
            CommonService.update(clientInterface, response.getPath(), entity);
        }
    }
}
